﻿using CommonBase;
using EnvCommonUtility;
using EnvControlLib;
using FileLib;
using InteractiveWhiteboardManagement.Base.ViewModels;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.Prism.ViewModel;
using RemotingObject;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;

namespace TreeMgtModule.ViewModels
{
    /// <summary>
    /// 远程监控画面
    /// </summary>
    public class ViewModel_MonitorScreen : WorkspaceViewModel
    {
        #region 常量

        private readonly string SAVEPATH_SCREENSHOT = Path.Combine(
            Environment.CurrentDirectory, "ScreenShot"); // 截图文件保存默认路径
        private static readonly object _padlock = new Object();

        #endregion

        #region 变量

        private DelegateCommand _cmdStartRemotePC, _cmdStopRemotePC, _cmdShutDownRemotePC,
            _cmdLockRemoteScreen, _cmdUnLockRemoteScreen, _cmdSendMessage2RemotePC,
            _cmdCaptureRemoteScreen;
        private System.Timers.Timer _timerMonitor; // 循环帧画面

        #endregion

        #region 构造函数

        public ViewModel_MonitorScreen(IRegionManager regionManager)
        {
            base.BaseRegionManager = regionManager;
            base.ViewName = InteractiveWhiteboardManagement.Base.Common.ViewNames.TreeMgtModule_MonitorScreen;
            //base.HeaderTitle = "监控界面"; // 在 MonitorTitle 中已设置
            base.HeaderImageSource = string.Format(ConstantString.IMAGE_URL, "MonitorScreen");
            base.IsShowCloseButton = Visibility.Visible;
            FileOperation.CreatDirectory(SAVEPATH_SCREENSHOT); // 创建文件夹

            #region Monitor Timer
            _timerMonitor = new System.Timers.Timer();
            _timerMonitor.Interval = EnvUtilities.TimerMonitorScreen * 1000; // 以毫秒为单位
            _timerMonitor.Elapsed += (s, arg) =>
            {
                try
                {
                    lock (_padlock)
                    {
                        BitmapSource currentFrame = MonitorOperation.Instance.UpdateDisplay(RemoteMonitor); // 获取当前帧
                        if (currentFrame != null)
                        {
                            Application.Current.Dispatcher.BeginInvoke((Action)(() =>
                            {
                                MonitorSource = currentFrame;
                            }));
                        }
                    }
                }
                catch (System.Exception ex)
                {
#if DEBUG
                    Debug.WriteLine(ex.Message);
#endif
                    StopMonitor();
                    MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
                }
            };

            StartMonitor(); // 开始监控
            #endregion
        }

        #endregion

        #region Base Class Overrides

        protected override void OnDispose()
        {
            StopMonitor(); // 停止监控
        }

        #endregion

        #region 属性

        /// <summary>
        /// 开始监控
        /// </summary>
        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_StartRemotePC
        {
            get
            {
                if (_cmdStartRemotePC == null)
                {
                    _cmdStartRemotePC = new DelegateCommand(_startRemotePC, _canStartRemotePC);
                }
                return _cmdStartRemotePC;
            }
        }

        /// <summary>
        /// 停止监控
        /// </summary>
        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_StopRemotePC
        {
            get
            {
                if (_cmdStopRemotePC == null)
                {
                    _cmdStopRemotePC = new DelegateCommand(_stopRemotePC, _canStopRemotePC);
                }
                return _cmdStopRemotePC;
            }
        }

        /// <summary>
        /// 远程关机
        /// </summary>
        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_ShutDownRemotePC
        {
            get
            {
                if (_cmdShutDownRemotePC == null)
                {
                    _cmdShutDownRemotePC = new DelegateCommand(_shutDownRemotePC, _canShutDownRemotePC);
                }
                return _cmdShutDownRemotePC;
            }
        }

        /// <summary>
        /// 远程锁屏
        /// </summary>
        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_LockRemoteScreen
        {
            get
            {
                if (_cmdLockRemoteScreen == null)
                {
                    _cmdLockRemoteScreen = new DelegateCommand(_lockRemoteScreen, _canLockRemoteScreen);
                }
                return _cmdLockRemoteScreen;
            }
        }

        /// <summary>
        /// 远程解锁
        /// </summary>
        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_UnLockRemoteScreen
        {
            get
            {
                if (_cmdUnLockRemoteScreen == null)
                {
                    _cmdUnLockRemoteScreen = new DelegateCommand(_unLockRemoteScreen, _canUnLockRemoteScreen);
                }
                return _cmdUnLockRemoteScreen;
            }
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_SendMessage2RemotePC
        {
            get
            {
                if (_cmdSendMessage2RemotePC == null)
                {
                    _cmdSendMessage2RemotePC = new DelegateCommand(_sendMessage2RemotePC, _canSendMessage2RemotePC);
                }
                return _cmdSendMessage2RemotePC;
            }
        }

        /// <summary>
        /// 远程截图
        /// </summary>
        [Display(GroupName = "DelegateCommand")]
        public DelegateCommand Cmd_CaptureRemoteScreen
        {
            get
            {
                if (_cmdCaptureRemoteScreen == null)
                {
                    _cmdCaptureRemoteScreen = new DelegateCommand(_captureRemoteScreen, _canCaptureRemoteScreen);
                }
                return _cmdCaptureRemoteScreen;
            }
        }



        /// <summary>
        /// 远程主机代理对象
        /// </summary>
        public RemotingMonitor RemoteMonitor { get; set; }

        /// <summary>
        /// 所选树结点
        /// </summary>
        public ITreeGroup WorkingTreeNode { get; set; }

        /// <summary>
        /// 附加值
        /// </summary>
        public object Arg
        {
            get
            {
                if (WorkingTreeNode != null)
                    return WorkingTreeNode.Arg;
                else
                    return null;
            }
        }

        private bool _canRunRemotePC;
        /// <summary>
        /// 可执行远程操作
        /// </summary>
        public bool CanRunRemotePC
        {
            get
            {
                return _canRunRemotePC;
            }
            set
            {
                if (_canRunRemotePC == value) return;
                _canRunRemotePC = value;
                base.OnPropertyChanged("CanRunRemotePC");

                InteractiveWhiteboardManagement.Base.Reflector.WorkingStateProperty.OnWorkingStatePropertyChanged(this); // 更新界面
            }
        }

        private string _monitorTitle;
        /// <summary>
        /// 当前监控文字描述
        /// </summary>
        public string MonitorTitle
        {
            get
            {
                return _monitorTitle;
            }
            set
            {
                if (_monitorTitle == value) return;
                _monitorTitle = value;
                base.OnPropertyChanged("MonitorTitle");


                // 修改标题文字
                if (string.IsNullOrWhiteSpace(value))
                    base.HeaderTitle = "监控界面";
                else
                    base.HeaderTitle = value.Replace("当前监控：", string.Empty)
                        .Replace("客户端连接不成功：", string.Empty);
            }
        }

        private SolidColorBrush _monitorTitleColor;
        /// <summary>
        /// 文字描述颜色
        /// </summary>
        public SolidColorBrush MonitorTitleColor
        {
            get
            {
                return _monitorTitleColor;
            }
            set
            {
                if (_monitorTitleColor == value) return;
                _monitorTitleColor = value;
                base.OnPropertyChanged("MonitorTitleColor");
            }
        }

        private BitmapSource _monitorSource;
        /// <summary>
        /// 当前监控图片资源
        /// </summary>
        public BitmapSource MonitorSource
        {
            get
            {
                return _monitorSource;
            }
            set
            {
                if (_monitorSource == value) return;
                _monitorSource = value;
                base.OnPropertyChanged("MonitorSource");
            }
        }

        #endregion

        #region 私有方法

        #region DelegateCommand

        private bool _canStartRemotePC()
        {
            return !CanRunRemotePC;
        }

        private bool _canStopRemotePC()
        {
            return CanRunRemotePC;
        }

        private bool _canShutDownRemotePC()
        {
            return CanRunRemotePC;
        }

        private bool _canLockRemoteScreen()
        {
            return CanRunRemotePC;
        }

        private bool _canUnLockRemoteScreen()
        {
            return CanRunRemotePC;
        }

        private bool _canSendMessage2RemotePC()
        {
            return CanRunRemotePC;
        }

        private bool _canCaptureRemoteScreen()
        {
            return CanRunRemotePC;
        }


        /// <summary>
        /// 开始监控
        /// </summary>
        private void _startRemotePC()
        {
            try
            {
                if (WorkingTreeNode != null &&
                    WorkingTreeNode.Arg is TagModel &&
                    (WorkingTreeNode.Arg as TagModel).Status == LeafStatusEnum.LeafOK.ToString())
                {
                    StartMonitor();
                }
                else
                {
                    AutoCloseNoticeWindow.Show("客户端连接不成功", true);
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
        }

        /// <summary>
        /// 停止监控
        /// </summary>
        private void _stopRemotePC()
        {
            try
            {
                StopMonitor();
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
        }

        /// <summary>
        /// 远程关机
        /// </summary>
        private void _shutDownRemotePC()
        {
            try
            {
                if (WorkingTreeNode != null &&
                    WorkingTreeNode.Arg is TagModel &&
                    (WorkingTreeNode.Arg as TagModel).Status == LeafStatusEnum.LeafOK.ToString())
                {
                    ConfirmWindow cw = new ConfirmWindow("确认远程关机？");
                    cw.Closed += new EventHandler(_cw_ShutDownClosed);
                    cw.ShowDialog();
                }
                else
                {
                    AutoCloseNoticeWindow.Show("客户端连接不成功", true);
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
        }

        /// <summary>
        /// 远程锁屏
        /// </summary>
        private void _lockRemoteScreen()
        {
            try
            {
                if (WorkingTreeNode != null &&
                    WorkingTreeNode.Arg is TagModel &&
                    (WorkingTreeNode.Arg as TagModel).Status == LeafStatusEnum.LeafOK.ToString())
                {
                    ConfirmWindow cw = new ConfirmWindow("确认远程锁屏？");
                    cw.Closed += new EventHandler(_cw_LockClosed);
                    cw.ShowDialog();
                }
                else
                {
                    AutoCloseNoticeWindow.Show("客户端连接不成功", true);
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
        }

        /// <summary>
        /// 远程解锁
        /// </summary>
        private void _unLockRemoteScreen()
        {
            try
            {
                if (WorkingTreeNode != null &&
                    WorkingTreeNode.Arg is TagModel &&
                    (WorkingTreeNode.Arg as TagModel).Status == LeafStatusEnum.LeafOK.ToString())
                {
                    MonitorOperation.Instance.UnlockPC(RemoteMonitor);
                }
                else
                {
                    AutoCloseNoticeWindow.Show("客户端连接不成功", true);
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        private void _sendMessage2RemotePC()
        {
            try
            {
                if (WorkingTreeNode != null &&
                    WorkingTreeNode.Arg is TagModel &&
                    (WorkingTreeNode.Arg as TagModel).Status == LeafStatusEnum.LeafOK.ToString())
                {
                    MessageWindow mw = new MessageWindow(false);
                    mw.Closed += new EventHandler(_mw_SendMessageClosed);
                    mw.ShowDialog();
                }
                else
                {
                    AutoCloseNoticeWindow.Show("客户端连接不成功", true);
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
        }

        /// <summary>
        /// 远程截图
        /// </summary>
        private void _captureRemoteScreen()
        {
            try
            {
                new Thread(() =>
                {
                    if (!string.IsNullOrWhiteSpace(MonitorTitle) && 
                        WorkingTreeNode != null &&
                        WorkingTreeNode.Arg is TagModel &&
                        (WorkingTreeNode.Arg as TagModel).Status == LeafStatusEnum.LeafOK.ToString())
                    {
                        BitmapSource bitmap;
                        do
                        {
                            bitmap = MonitorOperation.Instance.UpdateDisplay(RemoteMonitor); // 获取当前帧
                        } while (bitmap == null);

                        string saveScreenShotFileName = Path.Combine(SAVEPATH_SCREENSHOT,
                            string.Format("{0}_{1}.png", MonitorTitle.Replace("当前监控：", string.Empty),
                            DateTime.Now.ToString("yyyyMMddHHmmss"))); // 保存的文件名称

                        BitmapEncoder encoder = new PngBitmapEncoder();
                        encoder.Frames.Add(BitmapFrame.Create(bitmap));

                        using (Stream pngStream = File.Create(saveScreenShotFileName))
                        {
                            encoder.Save(pngStream); // 保存 png 图片
#if DEBUG
                            Debug.WriteLine("截图成功！");
#endif
                            MessageBox.Show(string.Format("截图成功！\n保存位置：{0}",
                                saveScreenShotFileName), ConstantString.MSG_COMPANY);
                        }
                    }
                    else
                    {
                        AutoCloseNoticeWindow.Show("客户端连接不成功", true);
                    }
                }).Start();
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                MessageBox.Show(ex.Message, ConstantString.MSG_COMPANY);
            }
        }

        #endregion

        /// <summary>
        /// 锁屏关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _cw_LockClosed(object sender, EventArgs e)
        {
            if ((sender as ConfirmWindow).DialogResult != true)
                return;

            try
            {
                if (WorkingTreeNode != null &&
                    WorkingTreeNode.Arg is TagModel &&
                    (WorkingTreeNode.Arg as TagModel).Status == LeafStatusEnum.LeafOK.ToString())
                {
                    MonitorOperation.Instance.LockPC(RemoteMonitor);
                }
                else
                {
                    AutoCloseNoticeWindow.Show("客户端连接不成功", true);
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 关机关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _cw_ShutDownClosed(object sender, EventArgs e)
        {
            if ((sender as ConfirmWindow).DialogResult != true)
                return;

            try
            {
                if (WorkingTreeNode != null &&
                    WorkingTreeNode.Arg is TagModel &&
                    (WorkingTreeNode.Arg as TagModel).Status == LeafStatusEnum.LeafOK.ToString())
                {
                    MonitorOperation.Instance.ShutDownPC(RemoteMonitor);
                }
                else
                {
                    AutoCloseNoticeWindow.Show("客户端连接不成功", true);
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 发送消息关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _mw_SendMessageClosed(object sender, EventArgs e)
        {
            if ((sender as MessageWindow).DialogResult != true)
                return;

            try
            {
                if (WorkingTreeNode != null &&
                    WorkingTreeNode.Arg is TagModel &&
                    (WorkingTreeNode.Arg as TagModel).Status == LeafStatusEnum.LeafOK.ToString())
                {
                    string msg = (sender as MessageWindow).NoticeBoxText;
                    if (!string.IsNullOrWhiteSpace(msg))
                    {
                        MonitorOperation.Instance.SendMessage(RemoteMonitor, msg);
                    }
                }
                else
                {
                    AutoCloseNoticeWindow.Show("客户端连接不成功", true);
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
                MessageBox.Show(ex.Message);
            }
        }

        #endregion

        #region 公开的方法

        /// <summary>
        /// 开始监控
        /// </summary>
        public void StartMonitor()
        {
            try
            {
                MonitorTitleColor = new SolidColorBrush(Colors.White);
                CanRunRemotePC = true;
                _timerMonitor.Start();
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
        }

        /// <summary>
        /// 停止监控
        /// </summary>
        public void StopMonitor()
        {
            try
            {
                _timerMonitor.Stop();
                MonitorSource = null;
                CanRunRemotePC = false;
                MonitorTitleColor = new SolidColorBrush(Colors.Red);

                if (WorkingTreeNode != null &&
                    WorkingTreeNode.Arg is TagModel &&
                    (WorkingTreeNode.Arg as TagModel).Status == LeafStatusEnum.LeafOK.ToString())
                {
                    _unLockRemoteScreen(); // 解屏
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
        }

        #endregion
    }
}
